package com.collectplus.express.passport;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import droid.frame.utils.android.Log;

/**
 * Created by joker on 2017/11/7.
 * passport详情页适配器
 */
public class PassportDetailAdapter extends FragmentPagerAdapter {

    private List<PassportDetailFragment> fragmentsList;

    private FragmentManager manager;

    public PassportDetailAdapter(FragmentManager fm) {
        super(fm);
    }

    public PassportDetailAdapter(FragmentManager fm, List<PassportDetailFragment> fragments) {
        super(fm);
        this.manager = fm;
        this.fragmentsList = fragments;
    }

    @Override
    public int getCount() {
        return fragmentsList.size();
    }

    @Override
    public PassportDetailFragment getItem(int position) {
        return fragmentsList.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

    /**
     * 下面的所有代码都是用来判断加载过的数据不再重复加载
     * 在滑动viewpager的时候，会把前面的fragment的视图进行销毁执行{@link PassportDetailFragment#onDestroyView()}方法，所以进行了重新绘制界面，数据加载请求
     * 先判断要加载fragment是否已经加载到了{@link android.support.v4.app.FragmentTransaction}中，如果已经加载进去就直接取出来，否则直接进行添加
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        PassportDetailFragment fragment = fragmentsList.get(position);
        //判断当前的fragment是否已经被添加进入Fragmentanager管理器中
        if (!fragment.isAdded()) {
            FragmentTransaction transaction = manager.beginTransaction();
            Log.d("11111", fragment.getClass().getSimpleName() + position);
            transaction.add(fragment, fragment.getClass().getSimpleName() + position);
            //不保存系统参数，自己控制加载的参数
            transaction.commitAllowingStateLoss();
            //手动调用,立刻加载Fragment片段
            manager.executePendingTransactions();
        }
        if (fragment.getView().getParent() == null) {
            //添加布局
            container.addView(fragment.getView());
        }
        return fragment.getView();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //移除布局
        container.removeView(fragmentsList.get(position).getView());
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
